import React from 'react'
import PropTypes from 'prop-types'
import {routerRedux} from 'dva/router'
import {connect} from 'dva'
import {Button, Card, Col, Icon, message, Popconfirm, Row, Tabs} from 'antd'
import {Page} from 'components'
import queryString from 'query-string'
import List from './components/List'
import BargainList from './components/BargainList'
import StarList from './components/StarList'
import DeletedList from './components/DeletedList'
import Filter from './components/Filter'
import Modal from './components/Modal'

const {TabPane} = Tabs

class Customer extends React.Component {

  constructor () {
    super()
    this.state = {
      activeKey: "customer",
    }
  }

  openTab = (record) => {
    const {dispatch} = this.props
    const tab = {
      name: '好友-'.concat(record.friendRemark || record.friendNickname),
      route: '/customer/'.concat(record.id),
    }
    dispatch({
      type: 'app/addTab',
      payload: {
        menu: tab,
      },
    })
  }

  render () {
    const {
      location, dispatch, customer, starModel, deleteModel, bargainModel, loading,
    } = this.props

    const {query, pathname} = location
    const {
      list,
      empList,
      customerChannelList,
      friendTypeList,
      addWaysList,
      friendCirclePermissionList,
      departments,
      pagination,
      expandForm,
      currentItem,
      modalVisible,
      modalType,
      stat,
      selectedRowKeys,
    } = customer

    const ColProps = {
      xs: 24,
      sm: 12,
      style: {
        marginBottom: 16,
      },
    }

    const {
      list: starList,
      pagination: starPagination,
    } = starModel

    const {
      list: deleteList,
      pagination: deletePagination,
    } = deleteModel

    const {
      list: bargainList,
      pagination: bargainPagination,
    } = bargainModel

    const {activeKey} = this.state

    const tabParam = (key, payload) => {
      if (key === "bargain") {
        payload.orderCount = 1
      } else if (key === 'star') {
        payload.isStar = 1
      } else if (key === 'delete') {
        payload.deleteHe = 1
      }
    }

    const handleRefresh = (newQuery) => {
      if (activeKey !== 'customer') {
        tabParam(activeKey, newQuery)

        dispatch({
          type: `${activeKey}Model/query`,
          payload: {...newQuery},
        })
      } else {
        dispatch(routerRedux.push({
          pathname,
          search: queryString.stringify({
            ...query,
            ...newQuery,
          }),
        }))
      }
    }

    const handleTabChange = (key) => {
      this.setState({
        activeKey: key,
      })

      let url = key
      const payload = {}
      if (key !== "customer") {
        url = `${key}Model/query`
        tabParam(key, payload)
      }

      dispatch({
        type: `${url}`,
        payload,
      })
    }

    const modalProps = {
      item: modalType === 'create' ? {} : currentItem,
      visible: modalVisible,
      width: 1600,
      maskClosable: false,
      confirmLoading: loading.effects[`customer/${modalType}`],
      title: '新增微信好友',
      wrapClassName: 'vertical-center-modal',
      onOk (data) {
        dispatch({
          type: `customer/${modalType}`,
          payload: data,
        })
          .then(() => {
            handleRefresh()
          })
      },
      onCancel () {
        dispatch({
          type: 'customer/hideModal',
        })
      },
    }

    const listProps = {
      rowKey: 'id',
      dataSource: list,
      loading: loading.effects['customer/query'],
      pagination,
      location,
      dispatch,
      onChange (page) {
        handleRefresh({
          current: page.current,
          size: page.pageSize,
        })
      },
      openTab: this.openTab,
      onCreateOrder (record) {
        if (!(record.operatorWxId || record.operatorWxId.belongEmp)) {
          message.warn("请先将运营号关联至员工")
          return
        }
        const friendName = record.friendRemark || record.friendNickname
        const tab = {
          name: '创建订单-' + friendName,
          route: '/orderForm/' + record.id,
        }
        dispatch({
          type: 'app/addTab',
          payload: {
            menu: tab,
          },
        })
        dispatch({
          type: 'createOrder/saveDetail',
          payload: {
            formType: 'create',
            current: {
              customer: {
                belongEmpName: record.operatorWxId.belongEmp.name,
                friendName: record.friendRemark || record.friendNickname,
                operator: record.operatorWxId.remark || record.operatorWxId.nickname || record.operatorWxId.wxNo || record.operatorWxId.wxId,
                ...record,
              },
            },
          },
        })
      },
      rowSelection: {
        selectedRowKeys,
        onChange: (keys) => {
          dispatch({
            type: 'customer/updateState',
            payload: {
              selectedRowKeys: keys,
            },
          })
        },
      },
    }

    const filterProps = {
      filter: {
        ...query,
      },
      stat,
      expandForm,
      empList,
      customerChannelList,
      friendTypeList,
      addWaysList,
      friendCirclePermissionList,
      departments,
      handleSearch (key) {
        if (key) {
          dispatch({
            type: 'customer/searchEmp',
            payload: {
              key,
            },
          })
        }
      },
      toggleForm () {
        dispatch({type: 'customer/toggleForm'})
      },
      onFilterChange (value) {
        handleRefresh({
          ...value,
          current: 1,
        })
      },
    }

    const bargainListProps = {
      location,
      loading,
      dispatch,
      bargainList,
      openTab: this.openTab,
      bargainPagination,
    }

    const starListProps = {
      location,
      loading,
      dispatch,
      openTab: this.openTab,
      starList,
      starPagination,
    }

    const deleteListProps = {
      location,
      loading,
      deleteList,
      dispatch,
      openTab: this.openTab,
      deletePagination,
    }

    const handleDeleteItems = () => {
      dispatch({
        type: 'customer/multiDelete',
        payload: {
          ids: selectedRowKeys,
        },
      })
        .then(() => {
          handleRefresh({
            current: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
        })
    }

    return (
      <div>
        <Row gutter={24}>
          <Card style={{marginBottom: 12}}>
            <Filter {...filterProps}/>
          </Card>
        </Row>
        <Row gutter={24}>
          <Page inner>
            {/*<Row gutter={24}>*/}
              {/*<Col {...ColProps} xl={{span: 8}} md={4} sm={24}>*/}
              {/*</Col>*/}
              {/*<Col {...ColProps} xl={{span: 8}} md={4} sm={24}>*/}
              {/*</Col>*/}
              {/*<Col span={8}>*/}
                {/*<a href="javascript:alert('下载模板')" target="_blank">*/}
                  {/*<Button className="margin-right">批量设置好友渠道</Button>*/}
                {/*</a>*/}
                {/*<a href="javascript:alert('好友导出')" target="_blank">*/}
                  {/*<Button className="margin-right"><Icon type="cloud-download-o"/>导出已删除好友</Button>*/}
                {/*</a>*/}
              {/*</Col>*/}
            {/*</Row>*/}
            {
              selectedRowKeys.length > 0 &&
              <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
                <Col>
                  {`选中了 ${selectedRowKeys.length} 条数据`}
                  <Popconfirm title="确定要删除这些数据吗?" placement="left" onConfirm={handleDeleteItems}>
                    <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                  </Popconfirm>
                </Col>
              </Row>
            }
            <Tabs activeKey={activeKey} onChange={handleTabChange}>
              <TabPane tab={'所有好友'} key={'customer'}>
                <List {...listProps} />
              </TabPane>
              <TabPane tab={'成交好友'} key={'bargain'}>
                <BargainList {...bargainListProps} />
              </TabPane>
              <TabPane tab={'星标好友'} key={'star'}>
                <StarList {...starListProps} />
              </TabPane>
              <TabPane tab={'已删除好友'} key={'delete'}>
                <DeletedList {...deleteListProps} />
              </TabPane>
            </Tabs>
            {modalVisible && <Modal {...modalProps} />}
          </Page>
        </Row>
      </div>
    )
  }
}

Customer.propTypes = {
  customer: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({customer, starModel, deleteModel, bargainModel, loading}) => ({
  customer,
  starModel,
  deleteModel,
  bargainModel,
  loading,
}))(Customer)
